<?php
// +----------------------------------------------------------------------
// | SL 2018.8.17
// +----------------------------------------------------------------------
// | Copyright (c) 2018~2018 http://sl.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: zq <1040657944@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;


use app\common\model\RoleModel;
use app\common\model\UserModel;
use think\Controller;

class User extends Base
{
    /**
     * 管理员列表
    */
    public function index()
    {
        if(request()->isAjax()){
            $role = new RoleModel();
            $param = input("param.");
            $where = [];
            // $where['role_id'] = ['neq',1];
            $limit = $param['limit'];
            $offset = ($param['page'] - 1) * $limit;
            $user = new UserModel();
            $user_list = $user->getAllUsers($where,$offset,$limit);
            foreach($user_list as $key=>$vo){
                $role_info = $role->getOneRole(['role_id' => $vo['role_id']]);
                $user_list[$key]['role_id'] = $role_info['role_name'];
                $user_list[$key]['operate'] = showOperate($this->makeButton($vo['id'],$role_info['role_id']));
            }

            $return['count'] = $user->getAllUsersCount($where);  //总数据
            $return['code'] = "0"; //状态码
            $return['data'] = $user_list;
            return json($return);
        }
        return $this->fetch();
    }

    /**
     * 添加管理员
    */
    public function addUser()
    {
        if(request()->isPost()){
            $param = input("post.");
            $user = new UserModel();
            $flag = $user->insertUser($param);
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }

        $role = new RoleModel();
        $role_list = $role->getAllRole();
        $this->assign([
            'role_list' => $role_list
        ]);
        return $this->fetch();
    }

    /**
     * 编辑管理员
    */
    public function editUser()
    {
        $user = new UserModel();
        $role = new RoleModel();
        if(request()->isPost()){
            $param = input("post.");
            $flag = $user->editUser($param);
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        $id = input("param.id");
        $user_info = $user->getOneUser(['id'=>$id]);
        // var_dump($user_info);exit;
        $this->assign([
            'user_info' => $user_info,
            'role_list' => $role->getAllRole()
        ]);
        return $this->fetch();
    }

    /**
     * 删除数据
    */
    public function userDel()
    {
        $id = input("param.id");
        $user = new UserModel();
        $flag = $user->delUser($id);
        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }

    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($id,$role_id)
    {
        $this->admin_info = session('admin_info');
        $role = new RoleModel();
        $arr = $role->getAllRole();
        $childs = $this->tree($arr,$this->admin_info['role_id']);
        $role_ids = [];
        foreach ($childs as $child) {
            $role_ids[] = $child['role_id'];
        }
        if (in_array($role_id, $role_ids)) {
 
            return [
                '编辑' => [
                    'auth' => 'user/edituser',
                    'href' => url('user/edituser', ['id' => $id]),
                    'btnStyle' => 'normal',
                    'icon' => 'fa fa-paste'
                ],
                '删除' => [
                    'auth' => 'user/userdel',
                    'href' => "javascript:userDel(" .$id .")",
                    'btnStyle' => 'danger',
                    'icon' => 'fa fa-trash-o'
                ]
            ];
        }else{
            return '';
        }
    }
    /**
    *@author MR.
    *修改用户密码
    **/
    public function changepwd()
    {
        if (request()->isPost()) {
            $param = input("post.");
            $where = [
                'password' =>  md5($param['oldpassword'] . config('salt')),
                'username' => session('admin_info.username')
            ];
            $user = new UserModel();
            $getOne = $user->getOneUser($where);
            if (!$getOne) {
                $this->error('旧密码错误！');
            }
            if ($param['password'] !== $param['repassword']) {
                $this->error('两次输入的密码不一致！');
            }
            $editParam = [
                'id' => $getOne['id'],
                'password' => $param['password']
            ];


            $result =  $user->editUser($editParam);
            if ($result['code'] == 1) {
                $this->success('密码修改成功，下次登录请使用新密码！','');
            }else{
                $this->error('页面出错，请刷新重试！');
            }
        }
        $this->assign('vo',session('admin_info'));
        return $this->fetch('');
    }

    /**
    *个人资料
    **/
    public function userinfo()
    {
        $user = new UserModel();
        $where = [
                'username' => session('admin_info.username')
            ];
        $getOne = $user->getOneUser($where);
        if (request()->isPost()) {
            $param = input("post.");
            $result =  $user->userInfo($param);
            if ($result['code'] == 1) {
                $this->success('个人信息提交成功','');
            }else{
                $this->error('页面出错，请刷新重试！');
            }
        }

        $this->assign('vo',$getOne);
        return $this->fetch('');
    }

    /**
    *上传图片
    */
    public function upload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
//        $fileInfo = $file->getInfo();
//        $savename = substr(strrchr($fileInfo['name'],'.'),1);
        // 移动到框架应用根目录/public/upload/ 目录下
        $upload_path = ROOT_PATH . 'public' . DS .'static/admin/images/heads' ;
        $info = $file->validate(['size'=>100*1024,'ext'=>'jpg,png,gif'])->move($upload_path,UID);
        if($info){
            // 成功上传后 获取上传信息
            // 输出 jpg
            // echo $info->getExtension();
            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            // echo $info->getSaveName();
            // 输出 42a79759f284b767dfcb2a0197904287.jpg
            // echo $info->getFilename(); 
            $msg = '/static/admin/images/heads'. DS . $info->getSaveName();
            $result = [
                'code' => 0,
                'msg' => $msg
            ];            
            return json($result);
        }else{
            // 上传失败获取错误信息
            $result = [
                'code' => 1,
                'msg' => $file->getError()
            ]; 
            return json($result);
        }
    }


    /**
    *获取所有子孙节点
    *
    */
    public function tree($arr,$pid,$level=0)
    {
        static $tree = [];
        foreach ($arr as $v) {
           if ($v['group'] == $pid) {
               $v['level'] = $level;
               $tree[] = $v;
               $this->tree($arr,$v['role_id'],$level+1);
           }
        }
        return $tree;
    }

}